
const PORT = 8000;
const { Pool } = require('pg');
const pool = new Pool({
    user: 'postgres',
    host: 'project_data_base',
    //host: '127.0.0.1',
    database: 'postgres',
    password: '1234',
    port: 5432,
  });
class indication {
  /**
     * @swagger
     * components:
     *   schemas:
     *     Indication:
     *       type: object
     *       properties:
     *         id:
     *           type: integer
     *         value:
     *           type: number
     *         user_id:
     *           type: integer
     *         id_sensors:
     *           type: integer
     *         date_time:
     *           type: string
     *           format: date-time
     * 
     * /indication:
     *   get:
     *     tags: [Измерения]
     *     summary: Получение списка показаний
     *     parameters:
     *       - in: query
     *         name: limit
     *         schema:
     *           type: integer
     *         description: Количество элементов для возврата
     *       - in: query
     *         name: offset
     *         schema:
     *           type: integer
     *         description: Смещение для получения следующего набора элементов
     *       - in: query
     *         name: sensor
     *         schema:
     *           type: integer
     *         description: Идентификатор сенсора для фильтрации
     *     responses:
     *       200:
     *         description: Список показаний
     *         content:
     *           application/json:
     *             schema:
     *               type: object
     *               properties:
     *                 indications:
     *                   type: array
     *                   items:
     *                     $ref: '#/components/schemas/Indication'
     *                 next:
     *                   type: string
     *                   nullable: true
     *                 previous:
     *                   type: string
     *                   nullable: true
     *       500:
     *         description: Внутренняя ошибка сервера
     */
    async indicationGet (req, res) {
          try {
            const limit = req.query.limit || 10;
            const offset = req.query.offset || 0;
            const sensor = req.query.sensor || null
            const values = [];
            var queryText = `
            SELECT * FROM users as u right join indications as i on u.id = i.user_id join sensors as s on i.id_sensors=s.id left join equipment as e on e.eid=s.id_equipment
            where 1=1
            `;
            if (sensor !== null) {
              queryText += `AND s.id = $1`;
              values.push(sensor)
              console.log('print')
            }
        
            const result = await pool.query(queryText, values);
            const indications = result.rows;        
            const nextOffset = indications.length < limit ? 0 : parseInt(offset) + parseInt(limit);
            const previousOffset = parseInt(offset) - parseInt(limit) >= 0 ? parseInt(offset) - parseInt(limit) : null;

            const response = {
                indications,
              next: nextOffset === 0 ? null : `http://localhost:${PORT}/indication?limit=${limit}&offset=${nextOffset}`,
              previous: previousOffset === null? null : `http://localhost:${PORT}/indication?limit=${limit}&offset=${previousOffset}`,
            };
        
            res.json(response);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
        /**
     * @swagger
     * /indication:
     *   post:
     *     tags: [Измерения]
     *     summary: Создание нового показания
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             properties:
     *               value:
     *                 type: number
     *               user_id:
     *                 type: integer
     *               id_sensors:
     *                 type: integer
     *               date_time:
     *                 type: string
     *                 format: date-time
     *     responses:
     *       200:
     *         description: Новое показание создано
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/Indication'
     *       500:
     *         description: Внутренняя ошибка сервера
     */
    async indicationPost (req, res){
          try {
            const { value, id_sensors, date_time, comment } = req.body;
            const client = await pool.connect();
            const resultcl = await client.query('SELECT u.id FROM users as u join role as r on u.role_id=r.id WHERE u.email=$1', [req.user.email]);
            console.log(resultcl)
            const queryText = `
              INSERT INTO indications (value, user_id, id_sensors, date_time, comment)
              VALUES ($1, $2, $3, $4, $5)
              RETURNING *;
            `;
            const values = [value, resultcl.rows[0].id, id_sensors, date_time, comment];
        
            const result = await pool.query(queryText, values);
            const newindication = result.rows[0];
        
            res.json(newindication);
          } catch (error) {
            res.status(500).json({ error: error.message });
          }
        }
}

module.exports = new indication()